const express = require("express");

let router = express.Router();

function getRandom(x, y) {
  return Math.round(Math.random() * (y - x) + x);
}

// 1.0 获取筛选条件相关数据
router.get("/getCate", async (req, res) => {
  // 1.0 处理参数
  let { typeTag, pid } = req.query;

  let sql = ` select * from category where isdelete = 0 `;
  if (typeTag) {
    sql += ` and typeTag = '${typeTag}' `;
  }

  if (pid) {
    sql += ` and pid = ${pid} `;
  }

  // res.execSql(sql, (err, results) => {
  //   if (err) {
  //     return res.send({ code: 500, msg: err.message });
  //   }

  //   // 成功处理
  //   res.send({ code: 200, msg: `分类${typeTag}数据获取成功`, data: results });
  // });

  let results = await res.execSql(sql);

  res.send({ code: 200, msg: `分类${typeTag}数据获取成功`, data: results });
});

// 2.0 生成项目数据

// 1.0 获取筛选条件相关数据
router.get("/getprojectlist", async (req, res) => {
  // 1.0 处理参数 fid:使用技术栈id,timelng:项目时长，ptypeid:1级项目类型id,pid:具体项目id，格式为：1,2,3
  let { timelng, fid, ptypeid, pid } = req.query;

  try {
    let results = [];
    // 获取项目名称
    /*
      "data": [
          {
          "cid": 12,
          "cName": "人力资源管理系统（HRM）",
          "typeValue": null,
          "typeTag": "projecttype2",
          "typeName": "项目类型2级",
          "pid": 20,
          "sortno": 1,
          "isdelete": 0
          }
        ]
    */
    let projectList = await getProjectTitle(req, res); // 获取项目标题数组，将来以这个数组为基准，遍历生成所有的项目数据
    let projectIds = projectList.map((item) => item.cid).join(","); // 获取项目id字符串，用来获取其他数据项
    let projectDesc = await getProjectDesc(req, res, projectIds); // 获取项目描述数组
    let frameWorks = await getFrameWorkDesc(req, res); // 获取项目技术栈
    let projectModel = await getProjectModel(req, res, projectIds); // 获取项目模块
    let modelid = projectModel.map((item) => item.mid).join(","); // 获取模块id字符串，用来获取模块描述
    let modelDescs = await getModelDesc(req, res, modelid); // 获取模块描述

    // 遍历projectList，生成一个个项目描述
    projectList.forEach((project) => {
      // 构建对象模板，方便查看
      let obj = {
        project_name: "项目名称",
        project_time: "项目周期",
        project_framework: "项目技术",
        project_desc: "项目描述",
        project_model: "项目模块",
        project_duty: ["项目职责"],
      };

      // 给obj对象属性赋值
      obj.project_name = project.cName; // 项目名称

      obj.project_time = timelng + "个月"; //项目周期
      let fws = frameWorks.filter(
        (item) => item.projecttypeid == ptypeid && item.frameworkid == fid
      );
      if (fws.length > 0) {
        obj.project_framework = fws[getRandom(0, fws.length - 1)].desc; //项目技术
      }

      let projectDesc1 = projectDesc.filter((item) => item.cid == project.cid);
      if (projectDesc1.length > 0) {
        let pdescindex = getRandom(0, projectDesc1.length - 1);
        obj.project_desc = projectDesc1[pdescindex].projectDesc; //项目描述
      }

      let projectModel1 = projectModel.filter(
        (item) => item.cid == project.cid
      );
      obj.project_model = projectModel1.map((item) => item.mname).join(","); //项目所有模块

      let projectModelIDs = projectModel1.map((item) => item.mid);

      let modelDescs1 = modelDescs.filter(
        (item) => projectModelIDs.indexOf(item.mid) > -1
      );
      modelDescs1.sort((p, n) => p.mid > n.mid);

      // 随机获取模块id
      let modelIdArr = [];
      let count = 6; // 职责只生成6条
      if(projectModelIDs.length < count){
        count = projectModelIDs.length;
      }

      for (let i = 0; i < count; i++) {
        let randomIndex = getRandom(0, projectModelIDs.length - 1);
        let model_id = projectModelIDs[randomIndex];
        if (modelIdArr.indexOf(model_id) > -1) {
          count++;
        } else {
          modelIdArr.push(model_id); //随机生成的模块id放入数组
        }
      }
      // 遍历模块，随机取出该模块的职责描述
      let dutys = [];
      modelIdArr.forEach((modelid) => {
        let modelDescArr = modelDescs1.filter((item) => item.mid == modelid);
        let randomIndex = getRandom(0, modelDescArr.length - 1);
        let modelDesc = modelDescArr[randomIndex];
        if (modelDesc) {
          dutys.push(modelDesc);
        }
      });

      obj.project_duty = dutys; //项目职责

      results.push(obj); // 每个项目加入到结果数组中
    });

    res.send({ code: 200, msg: `数据获取成功`, data: results });
  } catch (err) {
    return res.send({ code: 500, msg: err });
  }
});

// 获取项目标题
async function getProjectTitle(req, res) {
  let { ptypeid, pid } = req.query;
  let sql = ` select * from category where isdelete = 0 `;

  if (!ptypeid && !pid) {
    throw new Error("项目大类和项目小类必须有一个要选择");
  }

  // 如果用户有指定具体项目，则生成这些项目
  if (pid) {
    sql += ` and cid in (${pid}) `;
  }

  if (!pid && ptypeid) {
    sql += ` and pid = ${ptypeid} `;
  }

  let results = await res.execSql(sql);
  return results;
}

// 获取项目描述
// projectidstr: 1,2,3
async function getProjectDesc(req, res, projectidstr) {
  let { fid } = req.query;
  let sql = ` select * from project_desc where isdelete = 0 and cid in (${projectidstr}) and fid=${fid} `;

  let results = await res.execSql(sql);
  return results;
}

// 获取项目技术栈
async function getFrameWorkDesc(req, res) {
  let { fid, ptypeid } = req.query;
  let sql = ` select * from technologygroup where isdelete = 0 and projecttypeid =${ptypeid} and frameworkid = ${fid} `;

  let results = await res.execSql(sql);
  return results;
}

// 获取项目模块
async function getProjectModel(req, res, projectidstr) {
  let sql = ` select * from project_model where isdelete = 0 and cid in (${projectidstr}) `;

  let results = await res.execSql(sql);
  return results;
}

// 获取项目职责
async function getModelDesc(req, res, modelids) {
  let sql = ` SELECT * from model_desc where isdelete = 0 and  mid in (${modelids}) `;

  let results = await res.execSql(sql);
  return results;
}

// 导出
module.exports = router;
